package models

import (
	"time"

	"golang.org/x/crypto/bcrypt"
	"gorm.io/gorm"
)

// 用户角色
const (
	RoleUser     = "user"     // 普通用户
	RoleSupport  = "support"  // 客服
	RoleAdmin    = "admin"    // 管理员
)

// User 表示系统中的用户
type User struct {
	ID        uint           `json:"id" gorm:"primaryKey"`
	Username  string         `json:"username" gorm:"type:varchar(50);uniqueIndex;not null"`
	Password  string         `json:"-" gorm:"type:varchar(255);not null"` // 密码不返回给前端
	Email     string         `json:"email" gorm:"type:varchar(100);uniqueIndex"`
	RealName  string         `json:"real_name" gorm:"type:varchar(50)"`
	Role      string         `json:"role" gorm:"type:varchar(20);default:user"`
	Avatar    string         `json:"avatar" gorm:"type:varchar(255)"`
	CreatedAt time.Time      `json:"created_at"`
	UpdatedAt time.Time      `json:"updated_at"`
	DeletedAt gorm.DeletedAt `json:"-" gorm:"index"`
}

// BeforeSave 在保存前对密码进行哈希
func (u *User) BeforeSave(tx *gorm.DB) error {
	if u.Password != "" {
		hashedPassword, err := bcrypt.GenerateFromPassword([]byte(u.Password), bcrypt.DefaultCost)
		if err != nil {
			return err
		}
		u.Password = string(hashedPassword)
	}
	return nil
}

// CheckPassword 验证密码是否正确
func (u *User) CheckPassword(password string) bool {
	err := bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(password))
	return err == nil
}

// TableName 设置表名
func (User) TableName() string {
	return "users"
} 